package com.lxq.autovolume

import android.content.Context
import android.content.IntentFilter
import android.media.AudioManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ProgressBar
import com.lxq.autovolume.broadcast.VolumeBroadcast

class MainActivity : AppCompatActivity() {

    lateinit var audioManager:AudioManager
    lateinit var volumeProgress:ProgressBar
    lateinit var localBroadcast:VolumeBroadcast
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initBroadcast()
    }

    fun initView(){
        audioManager= getSystemService(Context.AUDIO_SERVICE) as AudioManager
        volumeProgress=findViewById(R.id.volume_progress)
        volumeProgress.max=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        volumeProgress.progress = getVolumeValue()
        //Toast.makeText(this, "当前音量值="+getVolumeValue(), Toast.LENGTH_SHORT).show()
    }
    fun getVolumeValue():Int{
        return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
    }
    fun initBroadcast(){
        localBroadcast=VolumeBroadcast(this)
        var intentFilter=IntentFilter()
        intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION")
        registerReceiver(localBroadcast,intentFilter)
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(localBroadcast)
    }
}